import BraftEditor from 'braft-editor';
import type { FC } from 'react';
import { useEffect, useRef, useState } from 'react';
import { buildPreviewHtml } from './util';

import 'braft-editor/dist/index.css';
import styles from './index.less';

type TProps = {
  value?: any;
  onChange?: TAnyFunction;
};

const CommonEditor: FC<TProps> = (props) => {
  const { value = '<p></p>', onChange } = props;
  const [content, setContent] = useState(BraftEditor.createEditorState(value));
  const isFirst = useRef(true);

  const triggerChange = (changedValue: { content?: string }) => {
    onChange?.(changedValue.content);
  };

  const preview = () => {
    if (window.previewWindow) {
      window.previewWindow.close();
    }
    window.previewWindow = window.open();
    window.previewWindow.document.write(buildPreviewHtml(content));
    window.previewWindow.document.close();
  };

  const handleChange = (editorState) => {
    setContent(editorState);
    triggerChange({
      content: editorState.toHTML(),
    });
  };

  useEffect(() => {
    if (value && isFirst.current) {
      isFirst.current = false;
      const data = BraftEditor.createEditorState(value);
      setContent(data);
    }
  }, [value]);

  const excludeControls = ['media', 'emoji'];
  const extendControls = [
    {
      key: 'custom-button',
      type: 'button',
      text: '预览',
      onClick: preview,
    },
  ];

  return (
    <div className={styles.editorWrap}>
      <BraftEditor
        className={styles.myEditor}
        value={content}
        onChange={handleChange}
        excludeControls={excludeControls}
        extendControls={extendControls}
        placeholder="请输入正文内容"
      />
    </div>
  );
};

export default CommonEditor;
